package com.practice.xml.dom;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public final class XmlDocumentBuilderPractice {
	public static void run() {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse("book.xml");
			
			Element root = document.getDocumentElement();
			NodeList books = root.getChildNodes();
			for (int i = 0; i < books.getLength(); i++) {
				Node book = books.item(i);			
				if (book.getNodeType() == Node.ELEMENT_NODE &&
						book.getNodeName().equals("book")) {					
					printBook(book);
				}
			}
		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private static void printBook(Node book) {
		NamedNodeMap bookAttrs = book.getAttributes();
		for (int i = 0; i < bookAttrs.getLength(); i++) {
			Node bookAttr = bookAttrs.item(i);
			if (bookAttr.getNodeType() == Node.ATTRIBUTE_NODE) {
				System.out.println(String.format("%1$s: %2$s",
						bookAttr.getNodeName(), bookAttr.getNodeValue()));
			}
		}
		
		NodeList bookElements = book.getChildNodes();
		for (int j = 0; j < bookElements.getLength(); j++) {
			Node bookElement = bookElements.item(j);
			if (bookElement.getNodeType() == Node.ELEMENT_NODE) {
				System.out.println(String.format("%1$s: %2$s",
						bookElement.getNodeName(),bookElement.getTextContent()));
			}
		}
	}
}
